#!/bin/bash

# 测试巡检认证问题

echo "====================================="
echo "  巡检功能认证测试"
echo "====================================="
echo ""

API_BASE="http://localhost:8000/api"

# 颜色
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "1. 测试未认证访问巡检接口"
echo "-------------------------------------"
echo -n "访问 /api/host-inspection/ (无token) ... "

response=$(curl -s -w "\n%{http_code}" -X POST "$API_BASE/host-inspection/" \
  -H "Content-Type: application/json" \
  -d '{"host_ids":[]}')

http_code=$(echo "$response" | tail -n1)

if [ "$http_code" = "401" ]; then
    echo -e "${GREEN}✓ 正确${NC} (返回401，符合预期)"
else
    echo -e "${RED}✗ 错误${NC} (返回$http_code，应该是401)"
fi

echo ""
echo "2. 测试登录功能"
echo "-------------------------------------"

# 尝试使用默认凭证登录
echo "尝试登录 (username: admin, password: admin123)..."

login_response=$(curl -s -X POST "$API_BASE/login/" \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin123"}')

# 尝试提取token
token=$(echo "$login_response" | grep -o '"token":"[^"]*' | cut -d'"' -f4)

if [ -n "$token" ] && [ "$token" != "null" ]; then
    echo -e "${GREEN}✓ 登录成功${NC}"
    echo "Token: ${token:0:20}..."
    
    echo ""
    echo "3. 使用token测试巡检接口"
    echo "-------------------------------------"
    
    echo -n "访问 /api/host-inspection/ (带token) ... "
    
    auth_response=$(curl -s -w "\n%{http_code}" -X POST "$API_BASE/host-inspection/" \
      -H "Content-Type: application/json" \
      -H "Authorization: Token $token" \
      -d '{"host_ids":[]}')
    
    auth_http_code=$(echo "$auth_response" | tail -n1)
    
    if [ "$auth_http_code" = "200" ]; then
        echo -e "${GREEN}✓ 成功${NC} (返回200)"
    else
        echo -e "${YELLOW}! 注意${NC} (返回$auth_http_code)"
        if [ "$auth_http_code" = "500" ]; then
            echo "  可能是因为没有配置主机，但认证成功"
        fi
    fi
    
else
    echo -e "${RED}✗ 登录失败${NC}"
    echo "响应: $login_response"
    echo ""
    echo "请检查："
    echo "1. 是否创建了超级用户？"
    echo "   cd /aiops/backend"
    echo "   python3 manage.py createsuperuser"
    echo ""
    echo "2. 或者使用现有用户凭证"
fi

echo ""
echo "====================================="
echo "  解决方案"
echo "====================================="
echo ""
echo -e "${YELLOW}如果您看到401错误，请按以下步骤操作：${NC}"
echo ""
echo "1. 刷新浏览器页面 (F5)"
echo "   → 系统会自动跳转到登录页"
echo ""
echo "2. 重新登录"
echo "   → 输入用户名和密码"
echo ""
echo "3. 再次尝试巡检"
echo "   → 现在应该可以正常工作了"
echo ""
echo -e "${GREEN}已改进：${NC}"
echo "  ✓ 遇到401错误自动清理过期token"
echo "  ✓ 自动提示'登录已过期'"
echo "  ✓ 自动跳转到登录页"
echo ""
echo "查看详细说明："
echo "  /aiops/巡检401错误修复.md"
echo ""
